package com.kongshidian.ui.fragment;

import java.lang.ref.WeakReference;
import java.util.List;

import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.kongshidian.App;
import com.kongshidian.R;
import com.kongshidian.bean.PageEntity;
import com.kongshidian.bean.ShopAO;
import com.kongshidian.http.WebClient;
import com.kongshidian.http.WebException;
import com.kongshidian.ui.KSDProductListActivity;
import com.kongshidian.ui.view.AbsViewHolderAdapter;
import com.kongshidian.ui.view.RefreshViewLoadMoreProxy;
import com.kongshidian.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 所有空时店
 * @author ghg
 *
 */
public class AllKSDFragment extends BaseFragment implements OnLoadDataActionListener{
	
	PullToRefreshListView mRefreshListView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	private int nowPage = 1;
	private List<ShopAO> mBrands;
	private BrandListAdapter mAdapter;
	private RelativeLayout mEmptyRelat;
	private Handler mHandler = new MyHandler(this);
	
	@Override  
	public View onCreateView(LayoutInflater inflater, ViewGroup container,  
			Bundle savedInstanceState) { 
		return inflater.inflate(R.layout.fragement_allksd, container, false);  
	}  
	
	
	/**
	 * 创建以后做的事情
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		
		mEmptyRelat = (RelativeLayout) findViewById(R.id.brand_empty_relat);

		mRefreshListView = (PullToRefreshListView) findViewById(R.id.ksd_list);
		mRefreshListView.setEmptyView(mEmptyRelat);
		mRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));

		mAdapter = new BrandListAdapter(this.getActivity(),R.layout.item_search_list);
		mRefreshListView.setAdapter(mAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshListView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);
		mLoadMoreProxy.refreshing();
		
		mRefreshListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent,
					View view, int position, long id) {
				Intent intent = new Intent(getActivity(),KSDProductListActivity.class);
				intent.putExtra("ShopId", mAdapter.getData().get(position-1).getId()+"");
				startActivity(intent);
				
			}
			
		});
		
	}
	
	
	
	private class MyHandler extends Handler{
		
		private WeakReference<Fragment> mActivity;
		
		private MyHandler(Fragment activity){
			mActivity = new WeakReference<Fragment>(activity);
		}
		
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					mAdapter.update(mBrands);
					break;
				case 1:
					mAdapter.append(mBrands);
					break;

				default:
					break;
				}
			}
		}
	}
	
	
	private class BrandListAdapter extends AbsViewHolderAdapter<ShopAO>{

		public BrandListAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, ShopAO itemData) {
			ImageView mImage = getViewFromHolder(R.id.item_search_image);
			TextView mNameText = getViewFromHolder(R.id.item_search_name_txt);
			TextView mAddressText = getViewFromHolder(R.id.item_search_price_txt);

			ImageLoader.getInstance().displayImage(itemData.getImage(), mImage);
			mNameText.setText(itemData.getName());
			mAddressText.setText("地址："+itemData.getAddress());
		}

	}


	@Override
	public void onRefresh(int page) {
		updateBrandList(1, true);
	}
	@Override
	public void onLoadMore(int page) {
		nowPage++;
		updateBrandList(nowPage, false);
	}
	
	private void updateBrandList(final int pageNum,final boolean isRefresh){
		mLoadMoreProxy.loadDataActionComplete(false);

		new Thread(){
			public void run() {
				try{
					WebClient client = WebClient.getInstance(getActivity());

					PageEntity<ShopAO> entry = client.getShopListByUserId(pageNum, 10, "", "desc");
					int totlePage = entry.getTotalPages();

					mBrands = entry.getContent();
					if(pageNum > totlePage){
						App.showShortToast(R.string.the_end_page);
						return;
					}
				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
						mBrands = null;
					else
						e.printStackTrace();
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

		mLoadMoreProxy.loadDataActionComplete(true);
	}
	
}
